import { Button, Table, Popover, Modal, notification, message } from 'antd';
import { SyncOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import router from 'umi/router';
import { useRequest, useBoolean } from '@umijs/hooks';
import AuthComponent from '@/components/Authorized/AuthComponent';
import React, { useState, useEffect, Fragment } from 'react';
import VerifyStep from '../VerifyStep/index';
import MaintainTime from '../MaintainTime/index';
import styles from './style.less';
import { intervalTime } from '@/utils/utils'; //格式化时间

import { closeCompensation, getOrderAuditRecord, getOrderSceneList } from '../../service';

const { confirm } = Modal;
const ListOfClaims = props => {
	const { compensationD, compensationL, flightNumDate, queryCompensation } = props;
	// 设置确认发放按钮的禁用 和 启用
	const { state: disBtn, setTrue, setFalse } = useBoolean(true);
	// 设置编辑按钮的禁用 和 启用
	const { state: editBtn, setTrue: setEditTrue, setFalse: setEditFalse } = useBoolean(true);
	// 设置注销按钮的禁用 和 启用
	const { state: logoutBtn, setTrue: setLogoutTrue, setFalse: setLogoutFalse } = useBoolean(true);
	// 设置关闭按钮的禁用 和 启用
	const { state: closeBtn, setTrue: setCloseTrue, setFalse: setCloseFalse } = useBoolean(true);
	// 维护现场时间按钮的禁用 和 启用
	const { state: timeBtn, setTrue: setTimeTrue, setFalse: setTimeFalse } = useBoolean(true);
	// 维护现场时间id
	const [timeId, setTimeId] = useState('');
	// 维护现场时间弹框的显示
	const {
		state: toggleMaintainTime,
		setTrue: setToggleMaintainTimeTrue,
		setFalse: setToggleMaintainTimeFalse
	} = useBoolean(false);

	// 提交关闭补偿单数据
	const { run } = useRequest((params) => closeCompensation(params), {
		manual: true,
		onSuccess: () => {
			queryCompensation(flightNumDate);
			notification.success({
				message: '成功',
				duration: 3,
				description: '操作完成'
			})
			setTrue();
			setCloseTrue();
		}
	});

	// 注销的方法
	const { run: runLogoutFun } = useRequest((params) => closeCompensation(params), {
		manual: true,
		onSuccess: () => {
			queryCompensation(flightNumDate);
			notification.success({
				message: '成功',
				duration: 3,
				description: '操作完成'
			})
			setTrue();
			setLogoutTrue();
		}
	});

	// 获取审核信息
	const { run: shInfo, data: sData = [] } = useRequest(params => getOrderAuditRecord(params),
		{
			manual: true,
			onSuccess: () => {
				handleVerify(true);
			}
		}
	)
	// 打开维护现场时间弹框
	const openMaintainTimeFun = (data) => {
		setTimeId(data);
		setToggleMaintainTimeTrue();
	}
	useEffect(() => {
		setTrue();
		setCloseTrue();
		setLogoutTrue();
		setTimeTrue();
		handleKeys([]);
		handleRows([])
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [compensationD])

	const [verifystep, handleVerify] = useState(false);

	// 截取航段
	const filterContent = v => {
		let arr = v.split(',')
		if (arr.length === 1) {
			return (
				<div className={styles.popoverBox}>
					<p>
						<span>{v}</span>
					</p>
				</div>
			)
		}
		return (
			<div className={styles.popoverBox}>
				{
					arr.map((vl, index) => {
						return (
							<p key={index}>
								<span>{vl}</span>
							</p>
						)
					})
				}
			</div>
		)
	}

	// 补偿单列表
	const columns = [
		{
			title: '操作',
			dataIndex: 'option',
			width: 70,
			// hideInTable: !(AuthComponent.getAuth('compensation.index.auditPro')),
			render: (_, record) => [
				// <AuthComponent authCode="compensation.index.auditPro">
				<span onClick={() => {
					shInfo({
						orderId: record.orderId
					})
				}} style={{ cursor: "pointer" }}>
					<SyncOutlined />
				</span>
				//  </AuthComponent>
			],
		},
		{
			title: '补偿单状态',
			dataIndex: 'status',
			width: 100,
			render: v => (
				<>
					<span style={{ display: v === '0' ? 'block' : 'none' }}>草稿</span>
					<span style={{ display: v === '1' ? 'block' : 'none' }}>审核中</span>
					<span style={{ display: v === '2' ? 'block' : 'none' }}>通过</span>
					<span style={{ display: v === '3' ? 'block' : 'none' }}>生效</span>
					<span style={{ display: v === '4' ? 'block' : 'none' }}>已关闭</span>
					<span style={{ display: v === '5' ? 'block' : 'none' }}>未通过</span>
					<span style={{ display: v === '6' ? 'block' : 'none' }}>驳回</span>
					<span style={{ display: v === '7' ? 'block' : 'none' }}>待审核</span>
					<span style={{ display: v === '8' ? 'block' : 'none' }}>已逾期</span>
					<span style={{ display: v === '9' ? 'block' : 'none' }}>注销</span>
					<span style={{ display: v === '10' ? 'block' : 'none' }}>已发放</span>
				</>
			)
		},
		{
			title: '补偿类型',
			dataIndex: 'payType',
			width: 120,
			render: text => [
				<span style={{ display: text === '0' ? 'block' : 'none' }}>不正常航班</span>,
				<span style={{ display: text === '1' ? 'block' : 'none' }}>异常行李</span>,
				<span style={{ display: text === '2' ? 'block' : 'none' }}>旅客超售</span>
			],
			filters: [
				{
					text: '不正常航班',
					value: '0'
				},
				{
					text: '异常行李',
					value: '1'
				},
				{
					text: '旅客超售',
					value: '2'
				}
			],
			onFilter: (value, record) => value === record.payType
		},
		{
			title: '补偿子类型',
			dataIndex: 'compensateType',
			width: 120,
			render: (text, record) => {
				if (record.payType === '1') {
					return [
						<span style={{ display: text === '' ? 'block' : 'none' }}>全部</span>,
						<span style={{ display: text === '0' ? 'block' : 'none' }}>临时补偿</span>,
						<span style={{ display: text === '1' ? 'block' : 'none' }}>结案补偿</span>
					]
				}else{
					return '-'
				}
				
			},
		},
		{
			title: '补偿单号',
			dataIndex: 'orderId',
			width: 200
		},
		{
			title: '补偿航段',
			dataIndex: 'choiceSegment',
			width: 150,
			render: (text, record) => (
				<Popover placement="bottom" content={filterContent(text)} title="" trigger="hover">
					<span className={styles.ellipsis}>{text}</span>
				</Popover>
			)
		},
		{
			title: '执行人数',
			dataIndex: 'executeCount',
			width: 120
		},
		{
			title: '执行金额',
			dataIndex: 'executeMoney',
			ellipsis: true,
			width: 120
		},
		{
			title: '冻结人数',
			dataIndex: 'freezeCount',
			width: 120
		},
		{
			title: '申请人',
			dataIndex: 'applyUser',
			width: 120
		},
		{
			title: '申请时间',
			dataIndex: 'applyTime',
			ellipsis: true,
			width: 180
		},
		{
			title: '现场领取有效时间',
			dataIndex: 'effectiveTime',
			ellipsis: true,
			width: 180,
			render: (text, record) => {
				let timeStr = intervalTime(text || 0);
				return timeStr.substring(0, timeStr.indexOf('分') + 1);
			}
		},
		{
			title: '关闭人',
			dataIndex: 'closeUser',
			width: 120
		},
		{
			title: '关闭时间',
			dataIndex: 'closeTime',
			ellipsis: true,
			width: 180
		}
	];

	// 记录多选是的的Id
	const [selectKeys, handleKeys] = useState([]);
	const [selectRows, handleRows] = useState([]);

	// 确认发放逻辑
	const confirmation = () => {
		// if (selectRows[0].createId === localStorage.getItem('userId')) {
		confirm({
			centered: true,
			title: '提示',
			icon: <ExclamationCircleOutlined />,
			content: (
				<div style={{ fontSize: "16px" }}><span style={{ color: "#ff5a5a" }}>确认操作后，补偿单内旅客将可以通过线上、现金等渠道领取补偿金,</span> 你还要继续吗？</div>
			),
			onOk() {
				run({
					orderId: selectKeys[0],
					status: '3'
				})
			},
			onCancel() {
			},
		});
		// } else {
		// 	message.error('非补偿单创建人，无补偿金额发放权限')
		// }
	};
	// 注销逻辑
	const logoutBtnFun = () => {
		confirm({
			centered: true,
			title: (
				<div style={{ color: "#000", fontSize: "18px", fontWeight: "bold" }}>提示</div>
			),
			icon: <ExclamationCircleOutlined />,
			content: (
				<div style={{ fontSize: "16px" }}><span style={{ color: "#ff5a5a" }}>注销后，该补偿单将被作废并将不计入报表统计，请确认是否【继续】？</span></div>
			),
			onOk() {
				console.log('注销 :>> ', '注销');
				runLogoutFun({
					orderId: selectKeys[0],
					status: '9' // 9注销 10箱包发放
				})
			}
		});
	}
	// 关闭补偿单
	const closeForm = () => {
		// if (selectRows[0].createId === localStorage.getItem('userId')) {
		confirm({
			centered: true,
			title: (
				<div style={{ color: "#000", fontSize: "18px", fontWeight: "bold" }}>提示</div>
			),
			icon: <ExclamationCircleOutlined />,
			content: (
				<div style={{ fontSize: "16px" }}><span style={{ color: "#ff5a5a" }}>关闭补偿单后，补偿单内待领取旅客将无法通过线上、现金等渠道领取补偿金，</span> 你还要继续吗？</div>
			),
			onOk() {
				run({
					orderId: selectKeys[0],
					status: '4'
				})
			}
		});
		// } else {
		// 	message.error('您当前不是补偿单发起人，无补偿单关闭权限')
		// }
	};

	// 编辑补偿单表格
	const editTable = () => {
		// if (selectRows[0].createId === localStorage.getItem('userId')) {
		let indemnityFormState = {
			type: 'add',
			editInfo: {
				orderId: selectKeys[0],
				type: 'edit',
				selectRows: selectRows[0]
			}
		};
		window.localStorage.setItem('indemnityFormBackUrl', '/compensation/indemnitySheet');
		window.localStorage.setItem('indemnityFormState', JSON.stringify(indemnityFormState));
		router.push({
			pathname: '/compensation/indemnityForm',
			state: indemnityFormState
		});
		// } else {
		// 	message.error('非补偿单创建人，不能进行补偿单编辑')
		// }

	};
	// 表格多选事件
	const onSelectChange = (selectedRowKeys, selectedRows) => {
		selectedRowKeys.length ? setFalse() : setTrue();
		//编辑
		if (selectedRowKeys.length === 1 && (selectedRows[0].isShowReEdit === '1' || selectedRows[0].status === '0') && selectedRows[0].payType === '0') {
			setEditFalse();
		} else {
			setEditTrue();
		}
		//关闭补偿单
		if (selectedRowKeys.length === 1 && (selectedRows[0].status === '2' || selectedRows[0].status === '3')) {
			setCloseFalse();
		} else {
			setCloseTrue();
		}
		//注销（类型为异常行李---补偿单状态为通过或生效---该补偿单的旅客申领状态是【未领取】）
		if (selectedRowKeys.length === 1 &&
			selectedRows[0].payType === '1' &&
			(selectedRows[0].status === '2' || selectedRows[0].status === '3') &&
			(selectedRows[0].receiveStatus === '0')
		) {
			setLogoutFalse();
		} else {
			setLogoutTrue();
		}
		// 发放
		if (selectedRowKeys.length === 1 && (selectedRows[0].status === '2')) {
			setFalse();
		} else {
			setTrue();
		}
		//  维护现场时间
		if (selectedRowKeys.length === 1 && (selectedRows[0].status === '3')) {
			setTimeFalse();
		} else {
			setTimeTrue();
		}

		handleKeys(selectedRowKeys);
		handleRows(selectedRows)
	};
	return (
		<Fragment>
			<div className={styles.searchBar}>
				<span className={styles.title}>补偿单列表</span>
				<div className={styles.option}>
					<AuthComponent authCode="compensation.index.saveData">
						<Button disabled={editBtn} onClick={editTable} type="primary" icon="edit">编辑</Button>
					</AuthComponent>
					<AuthComponent authCode="compensation.index.giveout">
						<Button disabled={disBtn} onClick={confirmation} type="primary" icon="check-circle">确认发放</Button>
					</AuthComponent>
					<AuthComponent authCode="compensation.index.logout">
						<Button disabled={logoutBtn} onClick={logoutBtnFun} type="primary" icon="rest">注销</Button>
					</AuthComponent>
					<AuthComponent authCode="compensation.index.close">
						<Button disabled={closeBtn} onClick={closeForm} type="primary" icon="close">关闭</Button>
					</AuthComponent>
					<AuthComponent authCode="compensation.index.maintainTime">
						<Button disabled={timeBtn} type="primary" icon="form" onClick={() => {
							openMaintainTimeFun({ orderId: selectKeys[0] })
						}}>维护现场时间</Button>
					</AuthComponent>
				</div>
			</div>
			<Table
				rowSelection={
					(AuthComponent.getAuth('compensation.index.saveData') ||
						AuthComponent.getAuth('compensation.index.giveout') ||
						AuthComponent.getAuth('compensation.index.close') ||
						AuthComponent.getAuth('compensation.index.maintainTime'))
						? {
							// selectedRowKeys: [],
							selectedRowKeys: selectKeys,
							onChange: onSelectChange
						}
						: false
				}
				pagination={{
					showSizeChanger: true,
					showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`,
					total: compensationD.total
				}}
				className="single"
				size='small'
				rowKey="orderId"
				loading={compensationL}
				columns={columns}
				dataSource={compensationD.data}
				scroll={{ x: 1000, y: 300 }}
				onRow={record => {
					return {
						onDoubleClick: event => {
							if (AuthComponent.getAuth('compensation.index.showDetail')) {
								let indemnityFormState = {
									type: 'examine',
									orderId: record.orderId,
									status: record.status,
									selectRows: record
								};
								window.localStorage.setItem('indemnityFormBackUrl', '/compensation/indemnitySheet');
								window.localStorage.setItem('indemnityFormState', JSON.stringify(indemnityFormState));
								router.push({
									pathname: '/compensation/indemnityForm',
									state: indemnityFormState
								})
							}
						}
					}
				}}
			/>
			{/* 审核步骤 */}
			<VerifyStep sData={sData} handleVerify={handleVerify} modalVisible={verifystep} />
			{/* 维护现场时间 */}
			<MaintainTime
				timeId={timeId}
				modalVisible={toggleMaintainTime}
				setToggleMaintainTimeFalse={setToggleMaintainTimeFalse}
			/>
		</Fragment>
	)
}

export default ListOfClaims;
